package com.jams.goodox.activity.mine.image;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jams.goodox.R;
import com.jams.goodox.utils.FileUtil;
import com.jams.goodox.utils.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class SelectUpPopupWindow extends Activity implements OnClickListener {

	private Button btn_camera_photo, btn_select_photo, btn_cancel;
	private Button btn_delete_photo;
	private LinearLayout layout;
	private Intent intent;
	public static final int REQUEST_CODE_GALLERY = 0x1;
	public static final int REQUEST_CODE_TAKE_PICTURE = 0x2;
	public static final int REQUEST_CODE_CROP_IMAGE = 0x4;
	private File mFileTemp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alert_dialog);
		intent = getIntent();
		btn_camera_photo = (Button) this.findViewById(R.id.btn_camera_photo);
		btn_select_photo = (Button) this.findViewById(R.id.btn_select_photo);
		btn_cancel = (Button) this.findViewById(R.id.btn_cancel);
		btn_delete_photo = (Button) this.findViewById(R.id.btn_delete_photo);
		btn_delete_photo.setVisibility(View.GONE);

		layout = (LinearLayout) findViewById(R.id.pop_layout);

		// 添加选择窗口范围监听可以优先获取触点，即不再执行onTouchEvent()函数，点击其他地方时执行onTouchEvent()函数销毁Activity
		layout.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
//				ToastUtil.show(getApplicationContext(), R.string.click2close);
			}
		});
		// 添加按钮监听
		btn_cancel.setOnClickListener(this);
		btn_camera_photo.setOnClickListener(this);
		btn_select_photo.setOnClickListener(this);
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {

			File f = new File(Environment.getExternalStorageDirectory() + File.separator
					+ ImageUtil.DREAM + File.separator + "cache");
			if (!f.exists())
				f.mkdirs();

			mFileTemp = new File(Environment.getExternalStorageDirectory() + File.separator
					+ ImageUtil.DREAM + File.separator + "cache", "vhead.png");
		} else {

			File f = new File(getFilesDir() + File.separator
					+ ImageUtil.DREAM + File.separator + "cache");
			if (!f.exists())
				f.mkdirs();

			mFileTemp = new File(getFilesDir() + File.separator+ ImageUtil.DREAM + File.separator + "cache", "vhead.png");
		}
		if (!mFileTemp.exists()) try {
			mFileTemp.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// btn_delete_photo.setOnClickListener(this);
	}

	// 实现onTouchEvent触屏函数但点击屏幕时销毁本Activity
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 选择完或者拍完照后会在这里处理，然后我们继续使用setResult返回Intent以便可以传递数据和调用
		// if (data.getExtras() != null)
		// intent.putExtras(data.getExtras());
		if (requestCode == REQUEST_CODE_GALLERY) {
			try {

				InputStream inputStream = getContentResolver().openInputStream(data.getData());
				FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
				copyStream(inputStream, fileOutputStream);
				fileOutputStream.close();
				inputStream.close();

				startCropImage();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (requestCode == REQUEST_CODE_TAKE_PICTURE) {
			startCropImage();
		}
		if (requestCode == REQUEST_CODE_CROP_IMAGE) {
			String path = data.getStringExtra("image-path");
			if (path == null) {
				return;
			}
			intent.putExtra("cameraPath", path);
			intent.putExtra("cameraLag", "1");
			setResult(requestCode, intent);
			finish();
		}
	}

	public static void copyStream(InputStream input, OutputStream output) throws IOException {

		byte[] buffer = new byte[1024];
		int bytesRead;
		while ((bytesRead = input.read(buffer)) != -1) {
			output.write(buffer, 0, bytesRead);
		}
	}

	private void startCropImage() {

		Intent intent = new Intent(SelectUpPopupWindow.this, CropImage.class);
		intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
		intent.putExtra(CropImage.SCALE, true);
		intent.putExtra(CropImage.APP_CLIENT, 0);
		intent.putExtra(CropImage.ASPECT_X, 3);
		intent.putExtra(CropImage.ASPECT_Y, 3);

		startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
	}

	private void startPhoto() {
		if (isSdcardAvailable()) {
			FileUtil.getInstance(SelectUpPopupWindow.this).createFile(ImageUtil.ALBUM_PATH + File.separator + "cache");
		}
		File f = new File(Environment.getExternalStorageDirectory() + File.separator
				+ ImageUtil.DREAM + File.separator + "cache", "vhead.png");
		if (f.exists())
			f.delete();
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
	}

	private void takePicture() {
		if (!isSdcardAvailable()) {
			ToastUtil.showLong(SelectUpPopupWindow.this, "请插入SD卡");
			return;
		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		try {
			Uri mImageCaptureUri = null;
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				mImageCaptureUri = Uri.fromFile(mFileTemp);
			} else {
				/*
				 * The solution is taken from here:
				 * http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
				 */
				Uri CONTENT_URI = Uri.parse("content://eu.janmuller.android.simplecropimage.example/");
				mImageCaptureUri = CONTENT_URI;
			}
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

//	/**
//	 * 改变头像上传的角度问题
//	 */
//	private void changeAngle() {
//		int angle = BitmapUtils.readPictureDegree(cameraPath);
//		// 压缩图片
//		Bitmap bitmap = BitmapUtils.decodeFile(new File(cameraPath));
//		bitmap = BitmapUtils.changeDegree(bitmap, angle);
//		// 将转动后的图片写入原有图片并覆盖原有图片
//		BitmapUtils.saveJPGE_After(bitmap, cameraPath);
//	}

	@SuppressLint("NewApi")
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_camera_photo:
				if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
						!= PackageManager.PERMISSION_GRANTED) {
					//申请WRITE_EXTERNAL_STORAGE权限
					ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
							1991);
				} else {
					takePicture();
				}
				break;
			case R.id.btn_select_photo:
				if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
						|| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
					//申请WRITE_EXTERNAL_STORAGE权限
					List<String> permissionsNeeded = new ArrayList<String>();
					permissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
					permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
					ActivityCompat.requestPermissions(this,permissionsNeeded.toArray(new String[2]), 1991);
				} else {
					startPhoto();
				}

				break;
			case R.id.btn_cancel:
				finish();
				break;
			default:
				break;
		}
	}

	public static boolean isSdcardAvailable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		if (requestCode == 1991) {
			switch (permissions[0]){
				case Manifest.permission.CAMERA:
					if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
						takePicture();
					}else{
						if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
							MaterialDialog.Builder materialDialog = new MaterialDialog.Builder(this).content("相机必须要的权限，不开启将无法正常工作！").positiveText("确定").onPositive(new MaterialDialog.SingleButtonCallback() {
								@Override
								public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
									dialog.cancel();
								}
							});
							materialDialog.show();
							return;
						}
					}
					break;
				case Manifest.permission.WRITE_EXTERNAL_STORAGE:
				case Manifest.permission.READ_EXTERNAL_STORAGE:
					if(grantResults[0] == PackageManager.PERMISSION_GRANTED  &&  grantResults[1] == PackageManager.PERMISSION_GRANTED ){
						startPhoto();
					}else{
						if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)||
								!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE) ) {
							MaterialDialog.Builder materialDialog = new MaterialDialog.Builder(this).content("文件读取必须要的权限，不开启将无法正常工作！").
									positiveText("确定").onPositive(new MaterialDialog.SingleButtonCallback() {
								@Override
								public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
									dialog.cancel();
								}
							});
							materialDialog.show();
							return;
						}
					}
					break;
			}
		}
	}
}
